package com.sgb.merchant.view.activity;

import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.CountDownTimer;
import android.text.Html;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.util.Pair;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.sgb.link.entity.EventConstant;
import com.sgb.link.entity.MainEvent;
import com.sgb.link.entity.merchant.EnrolInfoEntiy;
import com.sgb.link.entity.merchant.InvestmentDetailEntity;
import com.sgb.link.router.PathMerchant;
import com.sgb.link.router.PathUser;
import com.sgb.link.view.widget.CustomXTabLayout;
import com.sgb.merchant.R;
import com.sgb.merchant.databinding.MerchantActivitySelfInverstmentDetailBinding;
import com.sgb.merchant.view.adapter.InvestmentDetailAdapter;
import com.sgb.merchant.viewmodel.InvestmentDetailViewModel;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.base.model.entity.SingleItemConstant;
import com.swgk.core.base.model.entity.SingleItemEntity;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 王彬臣
 * @date: 2021/8/11
 * @Description: 个人中心-投资项目详情
 */
@Route(path = PathMerchant.SelfInvestmentDetailActivity)
public class SelfInvestmentDetailActivity extends BaseActivity<InvestmentDetailViewModel, MerchantActivitySelfInverstmentDetailBinding> {
    private String[] titles = {"项目简介", "项目要求", "报名记录"};
    @Autowired(name = RouterKey.NO, desc = "详情no")
    long no;

    InvestmentDetailAdapter mAdapter;
    private List<SingleItemEntity> mList;
    private LinearLayoutManager mLinearLayoutManager;
    InvestmentDetailEntity entity;
    private CountDownTimer mTimer;
    private int lastPosition = -1; //用于判断recyclerView滑动的时候 是不是同一个item的位置
    private int mTabPosition = -1; //点击的tab的position
    private boolean isClickTab;
    private int id;//控件id

    @Override
    protected int layoutId() {
        return R.layout.merchant_activity_self_inverstment_detail;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(InvestmentDetailViewModel.class);

    }

    @Override
    protected void init() {

        ARouter.getInstance().inject(this);
        mBinding.includeTitle.titleView.setText("投资项目详情");
        mBinding.includeTitle.ivBack.setOnClickListener(v -> {
            finish();
        });
        mBinding.setClick(this);
        for (String title : titles) {
            mBinding.tablayout.addTab(mBinding.tablayout.newTab().setText(title));
        }
        mBinding.setLifecycleOwner(this);
        mLinearLayoutManager = new LinearLayoutManager(this);
        mBinding.rvContent.setLayoutManager(mLinearLayoutManager);
        mList = new ArrayList<>();
        mAdapter = new InvestmentDetailAdapter(mList, this);
        mAdapter.setSelf(true);
        mAdapter.bindToRecyclerView(mBinding.rvContent);
        //取消tab点击效果
        mBinding.tablayout.setTabRippleColor(ColorStateList.valueOf(getResources().getColor(R.color.transparent)));
        initEven();
        ininData();
    }

    private void initEven() {
        mBinding.rvContent.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //当滑动由recyclerView触发时，isClickTab 置true
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    isClickTab = false;
                }
                return false;
            }
        });
        mBinding.rvContent.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (isClickTab) {
                    return;
                }
                try {
                    int currentPosition = mLinearLayoutManager.findFirstVisibleItemPosition();
                    if (lastPosition != currentPosition) {
                        lastPosition = currentPosition;
                        //要滑动的时候 去判断点击的tab的位置跟recyclerView的可见位置做比较 取最大的 否则tab到不了指定点击的位置
                        currentPosition = Math.max(mTabPosition, currentPosition);
                        mBinding.tablayout.getTabAt(currentPosition).select();
                        mTabPosition = -1;//重置下 不然最大值的话 无法滑动
                    }

                } catch (Exception e) {

                }
            }
        });
        mBinding.tablayout.addOnTabSelectedListener(new CustomXTabLayout.SimpleSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                isClickTab = true;
                int position = tab.getPosition();
                mTabPosition = position;
                tipPosition(position);
            }
        });
    }


    //滑动到指定位置
    private void tipPosition(int position) {

        if (position == 1) {
            LinearLayoutManager mLayoutManager = (LinearLayoutManager) mBinding.rvContent.getLayoutManager();
            if (mLayoutManager != null) {
                mLayoutManager.scrollToPositionWithOffset(position, position);
            }

        } else {
            mBinding.rvContent.smoothScrollToPosition(position);
        }
        scrollToTop();
    }

    private void ininData() {
        DialogHelper.showProgressDialog(this, "加载中").setCanceledOnTouchOutside(true);
        mViewModel.getDetils(no);
        mViewModel.ldData.observe(this, data -> {
            entity = data;
            mList.clear();
            mBinding.coordinator.setVisibility(View.VISIBLE);
            mBinding.tvCodeNumber.setText(data.getItemCode());
            mBinding.tvTitle.setText(data.getItemName());
            mBinding.tvName.setText(data.getCompanyName());
/*            mBinding.tvType.setText(data.getIndustryName());
            mBinding.projectName.setText(TextUtils.isEmpty(data.getItemTypeName())?"/":data.getItemTypeName());
            mBinding.tvMoney.setText(data.getItemMoney() + "元");*/
            mBinding.tvPerson.setText(data.getLinkName());
            mBinding.tvPhone.setText(TextUtils.isEmpty(data.getLinkPhone())?"/":data.getLinkPhone());
            mBinding.tvCreateTime.setText(DateUtils.stampToDay6(data.getCreateTime()));
            mBinding.bidLayout.setVisibility(View.VISIBLE);
            if (data.getStatus().equals("0")) {
                mBinding.tvStatus.setText("已上架");
                mBinding.tvPutAway.setVisibility(View.GONE);
                mBinding.tvDel.setVisibility(View.GONE);
                mBinding.tvEdit.setVisibility(View.GONE);
                mBinding.tvDownAway.setVisibility(View.VISIBLE);
            } else {
                mBinding.tvStatus.setText("已下架");
                mBinding.tvPutAway.setVisibility(View.VISIBLE);
                mBinding.tvDel.setVisibility(View.VISIBLE);
                mBinding.tvEdit.setVisibility(View.VISIBLE);
                mBinding.tvDownAway.setVisibility(View.GONE);
            }

            List<String> pics = new ArrayList<>();
            if (data.getImages() != null) {
                for (InvestmentDetailEntity.ImagesBean pic : data.getImages()) {
                    pics.add(pic.getImageUrl());
                }
            }
            mList.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, data, pics));
            mList.add(new SingleItemEntity<InvestmentDetailEntity>(SingleItemConstant.TYPE_TWO, data));
            mAdapter.notifyDataSetChanged();
            mViewModel.getEnrolList(no);
        });
        mViewModel.ldList.observe(this, data -> {
            mList.add(new SingleItemEntity<EnrolInfoEntiy>(SingleItemConstant.TYPE_THREE, data));
            mAdapter.notifyDataSetChanged();
        });
        mAdapter.setToMoreClick(new InvestmentDetailAdapter.toMoreClick() {
            @Override
            public void toMore() {
                ActivityJump.startActivity(PathMerchant.EnrolListActivity, Pair.create(RouterKey.NO, no), Pair.create(RouterKey.TITLE, "报名记录"), Pair.create(RouterKey.BOOLEAN, true));
            }
        });
        mViewModel.ldDel.observe(this, success -> {
            EventBus.getDefault().post(MainEvent.make().setMessageTag(EventConstant.EVENT_MERCHANT_SELF_REFRESH));
            MToast.showToast(this, "删除成功");
            finish();
        });
        mViewModel.ldState.observe(this, state -> {
            switch (state) {//0未上架 1已删除 2正常
                case 1:
                    mBinding.coordinator.setVisibility(View.GONE);
                    mBinding.bidLayout.setVisibility(View.GONE);
                    mBinding.rlError.setVisibility(View.VISIBLE);
                    mBinding.noDataTv.setText(Html.fromHtml("当前数据已删除，请<u><font color='#5892FD'>返回列表</font></u>继续浏览吧~"));
                    mBinding.noDataTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            EventBus.getDefault().post(MainEvent.make().setMessageTag(EventConstant.EVENT_MERCHANT_SELF_REFRESH));
                            finish();
                        }
                    });
                    break;

            }
        });

        mViewModel.ldStatus.observe(this, result -> {
            if (!result) {
                new RoundDialog.Builder(this)
                        .title("温馨提示")
                        .content("该数据状态已发生变化，请刷新后再进行操作。")
                        .cancel("取消")
                        .confirm("确定")
                        .cancelable(false)
                        .confirmCallback(v12 -> mViewModel.getDetils(no)).show();
            }
        });
        mViewModel.ldUpdate.observe(this, result -> {
            if (entity.getStatus().equals("0")) {
                entity.setStatus("1");
            } else {
                entity.setStatus("0");
            }
            mViewModel.ldData.postValue(entity);
            //刷新列表页
            EventBus.getDefault().post(MainEvent.make().setMessageTag(EventConstant.EVENT_MERCHANT_SELF_REFRESH));
        });
    }

    public void countTime(long times, boolean isStart) {
        long dif = times - System.currentTimeMillis();
        mTimer = new CountDownTimer(dif, 1000) {
            public void onTick(long millisUntilFinished) {
                if (!isFinishing()) {
                    if (isStart) {
                        mBinding.tvTimes.setText("报名开始倒计时：" + DateUtils.dateDiff(DateUtils.stampToDay6(times)));
                    } else {
                        mBinding.tvTimes.setText("报名结束倒计时：" + DateUtils.dateDiff(DateUtils.stampToDay6(times)));
                    }
                }

            }

            public void onFinish() {
                if (!isFinishing()) {
                    mViewModel.getDetils(no);

                }
            }
        };
        mTimer.start();
    }

    public void scrollToTop() {
        //拿到 appbar 的 behavior,让 appbar 滚动
        ViewGroup.LayoutParams layoutParams = mBinding.appBarLayout.getLayoutParams();
        CoordinatorLayout.Behavior behavior =
                ((CoordinatorLayout.LayoutParams) layoutParams).getBehavior();
        if (behavior instanceof AppBarLayout.Behavior) {
            AppBarLayout.Behavior appBarLayoutBehavior = (AppBarLayout.Behavior) behavior;
            //拿到下方tabs的y坐标，即为我要的偏移量
            float y = mBinding.tablayout.getY();
            //注意传递负值
            appBarLayoutBehavior.setTopAndBottomOffset((int) -y);
        }

    }

    @Override
    public void onClick(View v) {
        id = v.getId();
        if (id == R.id.iv_map) {
            InvestmentDetailEntity entity = mViewModel.ldData.getValue();
            if (entity != null) {
                ARouter.getInstance().build(PathUser.MapPositionActivity)
                        .withDouble("latitude", Double.valueOf(entity.getLat()))
                        .withDouble("longitude", Double.valueOf(entity.getLng()))
                        .withString("companyName", entity.getCompanyName())
                        .withString("address", entity.getProviceName() + entity.getCityName() + entity.getRegionName() + entity.getAddressInfo())
                        .navigation();
            }
        } else if (id == R.id.tv_edit) {

            mViewModel.getDetailState(SelfInvestmentDetailActivity.this, no, 0, entity);

        } else if (id == R.id.tv_del) {

            mViewModel.getDetailState(SelfInvestmentDetailActivity.this, no, 3, entity);
        } else if (id == R.id.tv_down_away) {

            mViewModel.getDetailState(SelfInvestmentDetailActivity.this, no, 2, entity);
        } else if (id == R.id.tv_put_away) {

            mViewModel.getDetailState(SelfInvestmentDetailActivity.this, no, 1, entity);
        }


    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }

    }

    @Override
    public boolean isUseEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MainEvent event) {
        if (event.getMessageTag() == EventConstant.EVEN_MERCHANT_SELF_REFRESH_DETAIL) {
            mViewModel.getDetils(no);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 3000) {
                finish();
            }
        }
    }
}
